import {
  Leafer,
  Pen,
  DragEvent,
  App,
  Rect,
  Ellipse,
  Polygon,
  PointerEvent,
} from "leafer-ui";
import { ITool, TextBox } from "../types";
import { getSelectedTextBoxes } from "./boxSelect";
type RowRectangle = {
  rowIndex: number;
  x: number;
  y: number;
  width: number;
  height: number;
  pageIndex:number;
};

function generateRowRectangles(textBoxes: TextBox[]): RowRectangle[][] {
  // 1. 按 pageIndex 分组
  const pageMap = new Map<number, TextBox[]>();
  textBoxes.forEach(box => {
    const page = box.data.pageIndex;
    if (!pageMap.has(page)) pageMap.set(page, []);
    pageMap.get(page)!.push(box);
  });

  // 2. 获取所有pageIndex并排序
  const sortedPages = Array.from(pageMap.keys()).sort((a, b) => a - b);
  
  // 3. 为每个页面生成行矩形数组
  return sortedPages.map(pageIndex => {
    const pageBoxes = pageMap.get(pageIndex)!;
    
    // 3.1 在页面内按 rowIndex 分组
    const rowMap = new Map<number, TextBox[]>();
    pageBoxes.forEach(box => {
      const row = box.data.rowIndex;
      if (!rowMap.has(row)) rowMap.set(row, []);
      rowMap.get(row)!.push(box);
    });

    // 3.2 获取所有rowIndex并排序
    const sortedRows = Array.from(rowMap.keys()).sort((a, b) => a - b);
    
    // 3.3 生成当前页的行矩形数组
    return sortedRows.map(rowIndex => {
      const boxes = rowMap.get(rowIndex)!;
      
      // 计算当前行的边界
      let minX = Infinity;
      let minY = Infinity;
      let maxRight = -Infinity;
      let maxBottom = -Infinity;

      boxes.forEach(box => {
        minX = Math.min(minX, box.x);
        minY = Math.min(minY, box.y);
        maxRight = Math.max(maxRight, box.x + box.width);
        maxBottom = Math.max(maxBottom, box.y + box.height);
      });

      return {
        rowIndex,
        x: minX,
        y: minY,
        width: maxRight - minX,
        height: maxBottom - minY,
        pageIndex,
      };
    });
  });
}
const classNameObj = {
  'sr': 'selection-rect'
}
export const ShapeTool: ITool = ({ app, commit, target, imgList }) => {
  let isDrawing = false;
  let startPoint = { x: 0, y: 0 };
  let selectResult: {
    selectedTextBoxMap: Map<string, TextBox>;
    ranges: Array<TextBox>;
    selectedTextBoxes: TextBox[];
  } = {
    selectedTextBoxMap: new Map(),
    ranges: [],
    selectedTextBoxes: [],
  };
  let selectionRectList = []  
  const updateSelected = (selectedTextBoxMap: Map<string, TextBox>) => {
    // imgList.forEach((_, index) => {
    //   target(index).children.forEach((item) => {
    //     if (item.tag !== "Rect") return;
    //     if (selectedTextBoxMap.get(item.id)) {
    //       item.setAttr("fill", "red");
    //     } else {
    //       item.setAttr("fill", "transparent");
    //     }
    //   });
    // });
    // console.log(selectedTextBoxMap)
    if(selectionRectList.length){
      selectionRectList.forEach((item) => {
        item.remove();
      });
    }
    const res = generateRowRectangles(selectResult.selectedTextBoxes);
    selectionRectList = res.reduce((result,pageItem,pageIndex)=>{
      const list = pageItem.map((item)=>{
        return new Rect({
          x: item.x,
          y: item.y,
          width: item.width,
          height: item.height,
          fill: "red",
          strokeWidth: 1,
          zIndex: 100,
          opacity:0.2,
          className:classNameObj.sr,
        });
      })
      if(list.length){
        target(pageItem[0].pageIndex).addMany(list)
      }
      // result[pageIndex] = list;
      result = result.concat(list);
      return result
    },[] as any)

  };
  const startDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    if (app.editor.editing) return;
    console.log("startDrawing");
    if (e.target.tag !== "Rect") {
      selectResult = {
        selectedTextBoxMap: new Map(),
        ranges: [],
        selectedTextBoxes: [],
      };
      return updateSelected(new Map());
    }
    commit({
      selectedTextBoxMap: new Map(),
      ranges: [],
      selectedTextBoxes: [],
    });
    isDrawing = true;
    const point = e.getPagePoint();
    startPoint = { x: point.x, y: point.y };
  };
  const continueDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    if (!isDrawing) return;
    const point = e.getPagePoint();
    const boxes = imgList.map((_, index) => {
      return target(index).children.filter((i) => i.tag === "Rect"&&i.className!==classNameObj.sr);
    });
    selectResult = getSelectedTextBoxes({
      startX: startPoint.x,
      startY: startPoint.y,
      currentX: point.x,
      currentY: point.y,
      boxes,
      app,
      target,
    });
    updateSelected(selectResult.selectedTextBoxMap);
  };
  const stopDrawing = () => {
    isDrawing = false;
    commit(selectResult);
  };
  const eventsMap = {
    [DragEvent.START]: startDrawing,
    [DragEvent.DRAG]: continueDrawing,
    [DragEvent.END]: stopDrawing,
    [PointerEvent.CLICK]: (e) => {
      if (!selectResult.ranges.length) return;
      if (isDrawing) return;
      selectResult = {
        selectedTextBoxMap: new Map(),
        ranges: [],
        selectedTextBoxes: [],
      };
      updateSelected(new Map());
      commit(selectResult);
    },
  };
  return {
    eventsMap,
    active: () => {},
    deactive: () => {},
  };
};
